package com.hmdp.service.impl;

import com.fasterxml.jackson.databind.type.CollectionType;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.hmdp.content.ERRORContent.*;
import static com.hmdp.content.RedisConstants.LOCK_ORDER;
import static com.hmdp.content.RedisConstants.OREDER_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILLLOCK_SCRIPT;
    static {
        SECKILLLOCK_SCRIPT  = new DefaultRedisScript<>();
        SECKILLLOCK_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILLLOCK_SCRIPT.setResultType(Long.class);
    }

    private BlockingQueue<VoucherOrder> ordersTasks = new ArrayBlockingQueue<>(1024*1024);

    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void  init(){
            SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());

        SECKILL_ORDER_EXECUTOR.shutdown();
    }
    private class VoucherOrderHandler implements Runnable{

        @Override
        public void run() {
            while (true){
                //1.获取队列中的订单信息
                try {
                    VoucherOrder voucherOrder = ordersTasks.take();
                    //创建订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.info("处理的异常",e);
                }

            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
                  //创建锁对象
//        SimpleRedisLock redisLock = new SimpleRedisLock(stringRedisTemplate, LOCK_ORDER + userId);
        Long userId = voucherOrder.getUserId();
        RLock lock = redissonClient.getLock(LOCK_ORDER + userId);
        //获取锁
        boolean isLock = lock.tryLock();
        if (!isLock){
            //获取失败
            log.info(USER_ONLY_ONE);
            return ;
        }
        try{
             proxy.createVoucherOrder(voucherOrder);
        }finally {
            lock.unlock();
        }
    }

    private IVoucherOrderService proxy;
    /**
     * 秒杀下单
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        //1.查询优惠券
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        //2.判断秒杀是否开始
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
            //2.1秒杀还未开始
            return Result.fail(MIAOS_NOTIME);
        }
        //3.判断秒杀是否结束
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
            //秒杀已经结束
            return Result.fail(MIAOS_OVER);
        }
        //1执行lua脚本
        Long userId = UserHolder.getUser().getId();
        Long result = stringRedisTemplate.execute(
                SECKILLLOCK_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString()
        );
        //2判断结果是否为0
        int resultInt = result.intValue();
        if (resultInt != 0){
            //2.1不为0返回异常信息
            return Result.fail(resultInt == 1 ? STOCK_END : USER_ONLY_ONE);
        }
//        6.创建订单(订单id，用户id，优惠券id)
        VoucherOrder voucherOrder = new VoucherOrder();
        Long orderId = redisIdWorker.nextId(OREDER_KEY);
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
//        2.2为0有购买资格，把下单信息保存在阻塞队列
        //TODO 阻塞队列的添加
        ordersTasks.add(voucherOrder);
        //获取代理对象（本类事务）
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //返回订单id
        return  Result.ok(orderId);
    }

//    /**
//     * 秒杀下单
//     * @param voucherId
//     * @return
//     */
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //1.查询优惠券
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        //2.判断秒杀是否开始
//        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())){
//            //2.1秒杀还未开始
//            return Result.fail(MIAOS_NOTIME);
//        }
//        //3.判断秒杀是否结束
//        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())){
//            //秒杀已经结束
//            return Result.fail(MIAOS_OVER);
//        }
//        //4.判断库存是否充足
//        if (seckillVoucher.getStock() < 1){
//            //库存不足
//            return Result.fail(STOCK_END);
//        }
//        Long userId = UserHolder.getUser().getId();
//        //toString().intern()保证对象唯一
//          //创建锁对象
////        SimpleRedisLock redisLock = new SimpleRedisLock(stringRedisTemplate, LOCK_ORDER + userId);
//        RLock lock = redissonClient.getLock(LOCK_ORDER + userId);
//        //获取锁
//        boolean isLock = lock.tryLock();
//        if (!isLock){
//            //获取失败
//            return Result.fail(USER_ONLY_ONE);
//        }
//        try{
//            //获取代理对象（本类事务）
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        }finally {
//            lock.unlock();
//        }
//
//
//    }
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //4.1附加一人一单
            Long userId = voucherOrder.getUserId();
            Integer userOrderNum = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
            if (userOrderNum > 0) {
                //一个用户只能下单一个优惠券
                log.info(USER_ONLY_ONE);
                return ;
            }
            //5.扣减库存
            boolean succes = seckillVoucherService.update()
                    .setSql("stock = stock-1")
                    .eq("voucher_id", voucherOrder.getVoucherId())
                    .gt("stock", 0)
                    .update();
            if (!succes) {
                //扣减失败
                log.info(STOCK_ERROR);
                return;

            }
            //6.创建订单(订单id，用户id，优惠券id)
//            VoucherOrder voucherOrder = new VoucherOrder();
//            Long orderId = redisIdWorker.nextId(OREDER_KEY);
//            voucherOrder.setId(orderId);
//            voucherOrder.setUserId(userId);
//            voucherOrder.setVoucherId(voucherId);
            save(voucherOrder);


    }
    //非阻塞队列
//    @Transactional
//    public   Result createVoucherOrder(Long voucherId) {
//        //4.1附加一人一单
//        Long userId = UserHolder.getUser().getId();
//        Integer userOrderNum = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
//        if (userOrderNum > 0) {
//            //一个用户只能下单一个优惠券
//            return Result.fail(USER_ONLY_ONE);
//        }
//        //5.扣减库存
//        boolean succes = seckillVoucherService.update()
//                .setSql("stock = stock-1")
//                .eq("voucher_id", voucherId)
//                .gt("stock", 0)
//                .update();
//        if (!succes) {
//            //扣减失败
//            return Result.fail(STOCK_ERROR);
//
//        }
//        //6.创建订单(订单id，用户id，优惠券id)
//        VoucherOrder voucherOrder = new VoucherOrder();
//        Long orderId = redisIdWorker.nextId(OREDER_KEY);
//        voucherOrder.setId(orderId);
//        voucherOrder.setUserId(userId);
//        voucherOrder.setVoucherId(voucherId);
//        save(voucherOrder);
//        //7.返回订单id
//        return Result.ok(orderId);
//
//    }




}
